{% extends 'base.html' %}

{% block title %}编辑教练 - {{ coach.real_name }} - 乒乓球培训管理系统{% endblock %}

{% block page_title %}编辑教练{% endblock %}

{% block extra_css %}
<style>
    .form-container {
        max-width: 900px;
        margin: 0 auto;
        background: white;
        border-radius: 15px;
        padding: 2rem;
        box-shadow: 0 4px 15px rgba(0,0,0,0.1);
    }

    .form-header {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        margin-bottom: 2rem;
        padding-bottom: 1rem;
        border-bottom: 2px solid #f8f9fa;
    }

    .form-title-group {
        flex: 1;
    }

    .form-title {
        font-size: 1.5rem;
        font-weight: 700;
        color: #2c3e50;
        margin: 0;
    }

    .form-subtitle {
        color: #6c757d;
        font-size: 0.875rem;
        margin-top: 0.5rem;
    }

    .coach-info {
        background: #f8f9fa;
        border-radius: 8px;
        padding: 1rem;
        margin-left: 2rem;
        min-width: 200px;
    }

    .coach-id {
        font-size: 0.875rem;
        color: #6c757d;
        margin: 0;
    }

    .coach-status {
        padding: 0.25rem 0.75rem;
        border-radius: 15px;
        font-size: 0.75rem;
        font-weight: 600;
        margin-top: 0.5rem;
        display: inline-block;
    }

    .status-active {
        background: #d4edda;
        color: #155724;
    }

    .status-pending {
        background: #fff3cd;
        color: #856404;
    }

    .status-inactive {
        background: #f8d7da;
        color: #721c24;
    }

    .form-section {
        margin-bottom: 2rem;
    }

    .section-title {
        font-size: 1.1rem;
        font-weight: 600;
        color: #2c3e50;
        margin-bottom: 1rem;
        display: flex;
        align-items: center;
    }

    .section-title i {
        margin-right: 0.5rem;
        color: #007bff;
    }

    .form-row {
        margin-bottom: 1.5rem;
    }

    .form-label {
        font-weight: 600;
        color: #495057;
        margin-bottom: 0.5rem;
    }

    .form-control, .form-select {
        border-radius: 8px;
        border: 2px solid #e9ecef;
        padding: 0.75rem 1rem;
        transition: all 0.3s ease;
    }

    .form-control:focus, .form-select:focus {
        border-color: #007bff;
        box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);
    }

    .input-group-text {
        background: #f8f9fa;
        border: 2px solid #e9ecef;
        border-right: none;
        font-weight: 600;
        color: #495057;
    }

    .input-group .form-control {
        border-left: none;
    }

    .invalid-feedback {
        display: block;
        color: #dc3545;
        font-size: 0.875rem;
        margin-top: 0.25rem;
    }

    .form-text {
        color: #6c757d;
        font-size: 0.875rem;
        margin-top: 0.25rem;
    }

    .change-indicator {
        background: #fff3cd;
        border: 1px solid #ffeaa7;
        border-radius: 6px;
        padding: 0.5rem;
        margin-top: 0.5rem;
        font-size: 0.875rem;
        color: #856404;
    }

    .change-indicator i {
        margin-right: 0.5rem;
    }

    .photo-preview {
        width: 100px;
        height: 100px;
        border-radius: 50%;
        background: #f8f9fa;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-bottom: 1rem;
        overflow: hidden;
        border: 3px solid #e9ecef;
    }

    .photo-preview img {
        width: 100%;
        height: 100%;
        object-fit: cover;
    }

    .photo-preview i {
        font-size: 2rem;
        color: #6c757d;
    }

    .level-options {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
        gap: 1rem;
        margin-top: 0.5rem;
    }

    .level-option {
        position: relative;
        background: #f8f9fa;
        border: 2px solid #e9ecef;
        border-radius: 8px;
        padding: 1rem;
        cursor: pointer;
        transition: all 0.3s ease;
        text-align: center;
    }

    .level-option:hover {
        border-color: #007bff;
        background: #f0f8ff;
    }

    .level-option input[type="radio"] {
        position: absolute;
        opacity: 0;
    }

    .level-option input[type="radio"]:checked + .level-content {
        color: #007bff;
    }

    .level-option.selected {
        border-color: #007bff;
        background: #f0f8ff;
    }

    .level-icon {
        font-size: 1.5rem;
        margin-bottom: 0.5rem;
        display: block;
    }

    .level-label {
        font-weight: 600;
        font-size: 0.875rem;
    }

    .level-desc {
        font-size: 0.75rem;
        color: #6c757d;
        margin-top: 0.25rem;
    }

    .status-options {
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        gap: 1rem;
        margin-top: 0.5rem;
    }

    .status-option {
        position: relative;
        background: #f8f9fa;
        border: 2px solid #e9ecef;
        border-radius: 8px;
        padding: 1rem;
        cursor: pointer;
        transition: all 0.3s ease;
        text-align: center;
    }

    .status-option:hover {
        border-color: #007bff;
        background: #f0f8ff;
    }

    .status-option.selected {
        border-color: #007bff;
        background: #f0f8ff;
    }

    .status-option input[type="radio"] {
        position: absolute;
        opacity: 0;
    }

    .action-buttons {
        display: flex;
        gap: 1rem;
        justify-content: center;
        margin-top: 2rem;
        padding-top: 2rem;
        border-top: 2px solid #f8f9fa;
    }

    .btn-action {
        padding: 0.75rem 2rem;
        border-radius: 8px;
        font-weight: 500;
        transition: all 0.3s ease;
    }

    .btn-action:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 15px rgba(0,0,0,0.2);
    }

    .warning-box {
        background: #fff3cd;
        border: 1px solid #ffeaa7;
        border-radius: 8px;
        padding: 1rem;
        margin-bottom: 1.5rem;
    }

    .warning-title {
        font-weight: 600;
        color: #856404;
        margin-bottom: 0.5rem;
    }

    .warning-text {
        font-size: 0.875rem;
        color: #856404;
        margin: 0;
    }

    @media (max-width: 768px) {
        .form-container {
            margin: 1rem;
            padding: 1.5rem;
        }

        .form-header {
            flex-direction: column;
            gap: 1rem;
        }

        .coach-info {
            margin-left: 0;
            min-width: auto;
        }

        .action-buttons {
            flex-direction: column;
        }

        .btn-action {
            width: 100%;
        }

        .level-options {
            grid-template-columns: 1fr;
        }

        .status-options {
            grid-template-columns: 1fr;
        }
    }
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
    <!-- 编辑教练表单 -->
    <div class="form-container">
        <div class="form-header">
            <div class="form-title-group">
                <h1 class="form-title">编辑教练 - {{ coach.real_name }}</h1>
                <p class="form-subtitle">修改教练信息，更新资料和设置</p>
            </div>
            <div class="coach-info">
                <p class="coach-id">教练ID: #{{ coach.id }}</p>
                <span class="coach-status status-{{ coach.status }}">
                    {% if coach.status == 'active' %}在职
                    {% elif coach.status == 'pending' %}待审核
                    {% elif coach.status == 'inactive' %}离职
                    {% endif %}
                </span>
            </div>
        </div>

        <!-- 重要提醒 -->
        <div class="warning-box">
            <div class="warning-title">
                <i class="bi bi-exclamation-triangle me-2"></i>编辑提醒
            </div>
            <p class="warning-text">
                修改教练信息可能会影响现有的师生关系和课程预约。如果教练正在授课，建议在空闲时间进行编辑操作。
            </p>
        </div>

        <form method="POST" enctype="multipart/form-data" novalidate>
            {{ form.hidden_tag() }}

            <!-- 基本信息 -->
            <div class="form-section">
                <h5 class="section-title">
                    <i class="bi bi-person"></i>基本信息
                </h5>

                <div class="row">
                    <div class="col-md-8">
                        <div class="form-row">
                            {{ form.real_name.label(class="form-label") }}
                            {{ form.real_name(class="form-control" + (" is-invalid" if form.real_name.errors else "")) }}
                            {% if form.real_name.errors %}
                                {% for error in form.real_name.errors %}
                                <div class="invalid-feedback">{{ error }}</div>
                                {% endfor %}
                            {% endif %}
                            <div class="form-text">教练真实姓名，将在系统中显示给学员</div>
                        </div>

                        <div class="form-row">
                            {{ form.phone.label(class="form-label") }}
                            {{ form.phone(class="form-control" + (" is-invalid" if form.phone.errors else "")) }}
                            {% if form.phone.errors %}
                                {% for error in form.phone.errors %}
                                <div class="invalid-feedback">{{ error }}</div>
                                {% endfor %}
                            {% endif %}
                            <div class="form-text">当前手机号：{{ coach.phone }}</div>
                        </div>

                        <div class="form-row">
                            {{ form.email.label(class="form-label") }}
                            {{ form.email(class="form-control" + (" is-invalid" if form.email.errors else "")) }}
                            {% if form.email.errors %}
                                {% for error in form.email.errors %}
                                <div class="invalid-feedback">{{ error }}</div>
                                {% endfor %}
                            {% endif %}
                            <div class="form-text">当前邮箱：{{ coach.email or '未设置' }}</div>
                        </div>
                    </div>

                    <div class="col-md-4">
                        <div class="form-row">
                            {{ form.photo.label(class="form-label") }}
                            <div class="photo-preview">
                                {% if coach.photo_url %}
                                <img src="{{ coach.photo_url }}" alt="{{ coach.real_name }}" id="photoPreview">
                                {% else %}
                                <i class="bi bi-person-circle" id="photoPlaceholder"></i>
                                {% endif %}
                            </div>
                            {{ form.photo(class="form-control" + (" is-invalid" if form.photo.errors else "")) }}
                            {% if form.photo.errors %}
                                {% for error in form.photo.errors %}
                                <div class="invalid-feedback">{{ error }}</div>
                                {% endfor %}
                            {% endif %}
                            <div class="form-text">支持 JPG、PNG、GIF 格式</div>
                        </div>
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-6">
                        <div class="form-row">
                            {{ form.gender.label(class="form-label") }}
                            {{ form.gender(class="form-select" + (" is-invalid" if form.gender.errors else "")) }}
                            {% if form.gender.errors %}
                                {% for error in form.gender.errors %}
                                <div class="invalid-feedback">{{ error }}</div>
                                {% endfor %}
                            {% endif %}
                            <div class="form-text">当前性别：{{ '男' if coach.gender == 'male' else ('女' if coach.gender == 'female' else '未设置') }}</div>
                        </div>
                    </div>

                    <div class="col-md-6">
                        <div class="form-row">
                            {{ form.age.label(class="form-label") }}
                            {{ form.age(class="form-control" + (" is-invalid" if form.age.errors else "")) }}
                            {% if form.age.errors %}
                                {% for error in form.age.errors %}
                                <div class="invalid-feedback">{{ error }}</div>
                                {% endfor %}
                            {% endif %}
                            <div class="form-text">当前年龄：{{ coach.age or '未设置' }}岁</div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 职业信息 -->
            <div class="form-section">
                <h5 class="section-title">
                    <i class="bi bi-briefcase"></i>职业信息
                </h5>

                <div class="form-row">
                    {{ form.campus_id.label(class="form-label") }}
                    {{ form.campus_id(class="form-select" + (" is-invalid" if form.campus_id.errors else "")) }}
                    {% if form.campus_id.errors %}
                        {% for error in form.campus_id.errors %}
                        <div class="invalid-feedback">{{ error }}</div>
                        {% endfor %}
                    {% endif %}
                    <div class="form-text">
                        当前校区：{{ coach.campus.name if coach.campus else '未分配' }}
                        {% if current_user.is_campus_admin() %}
                        <div class="change-indicator">
                            <i class="bi bi-info-circle"></i>校区管理员只能将教练分配到自己管理的校区
                        </div>
                        {% endif %}
                    </div>
                </div>

                <div class="form-row">
                    {{ form.coach_level.label(class="form-label") }}
                    <div class="level-options">
                        {% for value, label in form.coach_level.choices %}
                            {% if value %}
                            <label class="level-option {% if form.coach_level.data == value %}selected{% endif %}">
                                <input type="radio" name="coach_level" value="{{ value }}" {% if form.coach_level.data == value %}checked{% endif %}>
                                <div class="level-content">
                                    {% if value == 'senior' %}
                                    <i class="bi bi-award level-icon" style="color: #007bff;"></i>
                                    <div class="level-label">高级教练</div>
                                    <div class="level-desc">经验丰富，技术精湛</div>
                                    {% elif value == 'middle' %}
                                    <i class="bi bi-star level-icon" style="color: #ffc107;"></i>
                                    <div class="level-label">中级教练</div>
                                    <div class="level-desc">教学熟练，技术过硬</div>
                                    {% elif value == 'junior' %}
                                    <i class="bi bi-bookmark level-icon" style="color: #28a745;"></i>
                                    <div class="level-label">初级教练</div>
                                    <div class="level-desc">基础扎实，认真负责</div>
                                    {% endif %}
                                </div>
                            </label>
                            {% endif %}
                        {% endfor %}
                    </div>
                    {% if form.coach_level.errors %}
                        {% for error in form.coach_level.errors %}
                        <div class="invalid-feedback">{{ error }}</div>
                        {% endfor %}
                    {% endif %}
                    <div class="form-text">
                        当前级别：
                        {% if coach.coach_level == 'senior' %}高级教练
                        {% elif coach.coach_level == 'middle' %}中级教练
                        {% elif coach.coach_level == 'junior' %}初级教练
                        {% else %}未设置
                        {% endif %}
                    </div>
                </div>

                <div class="form-row">
                    {{ form.hourly_rate.label(class="form-label") }}
                    <div class="input-group">
                        <span class="input-group-text">￥</span>
                        {{ form.hourly_rate(class="form-control" + (" is-invalid" if form.hourly_rate.errors else "")) }}
                        <span class="input-group-text">元/小时</span>
                    </div>
                    {% if form.hourly_rate.errors %}
                        {% for error in form.hourly_rate.errors %}
                        <div class="invalid-feedback">{{ error }}</div>
                        {% endfor %}
                    {% endif %}
                    <div class="form-text">当前费用：{{ coach.hourly_rate or '未设置' }}元/小时</div>
                </div>

                <div class="form-row">
                    {{ form.status.label(class="form-label") }}
                    <div class="status-options">
                        {% for value, label in form.status.choices %}
                        <label class="status-option {% if form.status.data == value %}selected{% endif %}">
                            <input type="radio" name="status" value="{{ value }}" {% if form.status.data == value %}checked{% endif %}>
                            <div class="status-content">
                                {% if value == 'active' %}
                                <i class="bi bi-check-circle" style="color: #28a745; font-size: 1.5rem; margin-bottom: 0.5rem;"></i>
                                <div style="font-weight: 600;">在职</div>
                                <div style="font-size: 0.75rem; color: #6c757d;">正常工作状态</div>
                                {% elif value == 'inactive' %}
                                <i class="bi bi-x-circle" style="color: #dc3545; font-size: 1.5rem; margin-bottom: 0.5rem;"></i>
                                <div style="font-weight: 600;">离职</div>
                                <div style="font-size: 0.75rem; color: #6c757d;">停止工作</div>
                                {% endif %}
                            </div>
                        </label>
                        {% endfor %}
                    </div>
                    {% if form.status.errors %}
                        {% for error in form.status.errors %}
                        <div class="invalid-feedback">{{ error }}</div>
                        {% endfor %}
                    {% endif %}
                    <div class="form-text">修改状态可能会影响现有的师生关系和预约</div>
                </div>
            </div>

            <!-- 个人档案 -->
            <div class="form-section">
                <h5 class="section-title">
                    <i class="bi bi-file-text"></i>个人档案
                </h5>

                <div class="form-row">
                    {{ form.bio.label(class="form-label") }}
                    {{ form.bio(class="form-control" + (" is-invalid" if form.bio.errors else "")) }}
                    {% if form.bio.errors %}
                        {% for error in form.bio.errors %}
                        <div class="invalid-feedback">{{ error }}</div>
                        {% endfor %}
                    {% endif %}
                    <div class="form-text">介绍教学理念、专长特色等，显示在教练档案页面</div>
                </div>

                <div class="form-row">
                    {{ form.experience.label(class="form-label") }}
                    {{ form.experience(class="form-control" + (" is-invalid" if form.experience.errors else "")) }}
                    {% if form.experience.errors %}
                        {% for error in form.experience.errors %}
                        <div class="invalid-feedback">{{ error }}</div>
                        {% endfor %}
                    {% endif %}
                    <div class="form-text">详细描述教学经验、获得的荣誉、专业资质等</div>
                </div>
            </div>

            <!-- 操作按钮 -->
            <div class="action-buttons">
                <a href="{{ url_for('coaches.detail', id=coach.id) }}" class="btn btn-secondary btn-action">
                    <i class="bi bi-arrow-left me-2"></i>取消编辑
                </a>

                <a href="{{ url_for('coaches.list') }}" class="btn btn-outline-secondary btn-action">
                    <i class="bi bi-list me-2"></i>返回列表
                </a>

                <button type="submit" class="btn btn-primary btn-action">
                    <i class="bi bi-check-circle me-2"></i>保存修改
                </button>
            </div>
        </form>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // 记录原始值
    const form = document.querySelector('form');
    const originalValues = {};

    form.querySelectorAll('input, select, textarea').forEach(field => {
        if (field.type === 'radio') {
            originalValues[field.name] = document.querySelector(`input[name="${field.name}"]:checked`)?.value;
        } else {
            originalValues[field.name] = field.value;
        }
    });

    // 检查表单是否有变更
    const checkFormChanges = function() {
        let hasChanges = false;

        form.querySelectorAll('input, select, textarea').forEach(field => {
            if (field.type === 'radio') {
                const currentValue = document.querySelector(`input[name="${field.name}"]:checked`)?.value;
                if (originalValues[field.name] !== currentValue) {
                    hasChanges = true;
                }
            } else if (field.type !== 'file' && originalValues[field.name] !== field.value) {
                hasChanges = true;
            }
        });

        // 更新提交按钮状态
        const submitBtn = document.querySelector('button[type="submit"]');
        if (hasChanges) {
            submitBtn.classList.remove('btn-primary');
            submitBtn.classList.add('btn-warning');
            submitBtn.innerHTML = '<i class="bi bi-exclamation-circle me-2"></i>保存修改';
        } else {
            submitBtn.classList.remove('btn-warning');
            submitBtn.classList.add('btn-primary');
            submitBtn.innerHTML = '<i class="bi bi-check-circle me-2"></i>保存修改';
        }

        return hasChanges;
    };

    // 为所有表单元素添加变更监听
    form.querySelectorAll('input, select, textarea').forEach(element => {
        element.addEventListener('input', checkFormChanges);
        element.addEventListener('change', checkFormChanges);
    });

    // 头像预览
    const photoInput = document.querySelector('input[name="photo"]');
    const photoPreview = document.getElementById('photoPreview');
    const photoPlaceholder = document.getElementById('photoPlaceholder');

    if (photoInput) {
        photoInput.addEventListener('change', function(e) {
            const file = e.target.files[0];
            if (file) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    if (photoPreview) {
                        photoPreview.src = e.target.result;
                        photoPreview.style.display = 'block';
                    } else {
                        // 创建新的图片元素
                        const img = document.createElement('img');
                        img.src = e.target.result;
                        img.id = 'photoPreview';
                        img.style.width = '100%';
                        img.style.height = '100%';
                        img.style.objectFit = 'cover';

                        const preview = document.querySelector('.photo-preview');
                        preview.innerHTML = '';
                        preview.appendChild(img);
                    }

                    if (photoPlaceholder) {
                        photoPlaceholder.style.display = 'none';
                    }
                };
                reader.readAsDataURL(file);
            }
        });
    }

    // 级别选项点击处理
    const levelOptions = document.querySelectorAll('.level-option');
    levelOptions.forEach(option => {
        option.addEventListener('click', function() {
            const radio = this.querySelector('input[type="radio"]');
            if (radio) {
                radio.checked = true;

                // 更新视觉状态
                levelOptions.forEach(opt => opt.classList.remove('selected'));
                this.classList.add('selected');

                // 触发变更检查
                checkFormChanges();
            }
        });
    });

    // 状态选项点击处理
    const statusOptions = document.querySelectorAll('.status-option');
    statusOptions.forEach(option => {
        option.addEventListener('click', function() {
            const radio = this.querySelector('input[type="radio"]');
            if (radio) {
                radio.checked = true;

                // 更新视觉状态
                statusOptions.forEach(opt => opt.classList.remove('selected'));
                this.classList.add('selected');

                // 触发变更检查
                checkFormChanges();
            }
        });
    });

    // 表单提交前验证和确认
    form.addEventListener('submit', function(e) {
        const hasChanges = checkFormChanges();

        if (!hasChanges) {
            alert('没有检测到任何修改，无需保存');
            e.preventDefault();
            return false;
        }

        const realName = document.querySelector('input[name="real_name"]').value;
        const phone = document.querySelector('input[name="phone"]').value;
        const campusId = document.querySelector('select[name="campus_id"]').value;
        const hourlyRate = document.querySelector('input[name="hourly_rate"]').value;

        // 验证必填字段
        if (!realName.trim()) {
            alert('请输入真实姓名');
            document.querySelector('input[name="real_name"]').focus();
            e.preventDefault();
            return false;
        }

        if (!phone.trim()) {
            alert('请输入手机号');
            document.querySelector('input[name="phone"]').focus();
            e.preventDefault();
            return false;
        }

        if (!campusId) {
            alert('请选择所属校区');
            document.querySelector('select[name="campus_id"]').focus();
            e.preventDefault();
            return false;
        }

        if (!hourlyRate || parseFloat(hourlyRate) <= 0) {
            alert('请输入有效的每小时费用');
            document.querySelector('input[name="hourly_rate"]').focus();
            e.preventDefault();
            return false;
        }

        // 保存确认
        if (!confirm('确定要保存这些修改吗？修改可能会影响现有的师生关系和预约。')) {
            e.preventDefault();
            return false;
        }

        // 防止重复提交
        const submitBtn = document.querySelector('button[type="submit"]');
        submitBtn.disabled = true;
        submitBtn.innerHTML = '<i class="bi bi-hourglass-split me-2"></i>保存中...';

        // 5秒后重新启用按钮
        setTimeout(() => {
            submitBtn.disabled = false;
            submitBtn.innerHTML = '<i class="bi bi-check-circle me-2"></i>保存修改';
        }, 5000);
    });

    // 页面离开前检查未保存的修改
    window.addEventListener('beforeunload', function(e) {
        if (checkFormChanges()) {
            e.preventDefault();
            e.returnValue = '您有未保存的修改，确定要离开吗？';
        }
    });

    // 数字输入框格式化
    const numberInputs = document.querySelectorAll('input[type="number"]');
    numberInputs.forEach(input => {
        input.addEventListener('input', function() {
            if (this.value < 0) this.value = 0;
        });
    });

    // 初始化检查
    checkFormChanges();
});
</script>
{% endblock %}